package com.leyou.trade.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.Carts;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {

    private final CartRepository cartRepository;

    public CartServiceImpl(CartRepository cartRepository) {

        this.cartRepository = cartRepository;
    }


    /**
     * 未识别用户版本
     *
     * @param carts
     */
    @Override
    public void addCart(Carts carts) {

        UserDetail user = UserContext.getUser();

        String id = buildId(carts.getSkuId(), user.getId());

        //1,查验当前商品是否已经加入过，没加过直接加，加过改数量


        Optional<Carts> cartsOptional = this.cartRepository.findById(id);

        //加过
        if (cartsOptional.isPresent()) {

            Carts storeCarts = cartsOptional.get();

            //之前的数量加入本次的数量
            storeCarts.setNum(storeCarts.getNum() + carts.getNum());

            this.cartRepository.save(storeCarts);
        }//没有加过，直接加
        else {
            carts.setId(id);
            carts.setUserId(user.getId());

            this.cartRepository.save(carts);
        }
    }

    @Override
    public String buildId(Long skuId, Long userId) {

        String format = "u%ds%d";

        return String.format(format, userId, skuId);
    }

    @Override
    public List<Carts> listCarts() {

        UserDetail user = UserContext.getUser();

        return this.cartRepository.findByUserId(user.getId());

    }

    @Override
    public void mergeCart(List<Carts> cartsList) {
        cartsList.forEach(this::addCart);
    }
}
